package com.xia.netty.thread.volatileExp;

public class VolatileExample {

    int a = 0;
    public void exchange(){
        a = 1;
    }

    public static void main(String[] args) {
        VolatileExample volatileExample = new VolatileExample();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+ "开始");
            try {//让主线程读取到内存中的a=0
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            volatileExample.exchange();
            System.out.println(Thread.currentThread().getName()+ "结束");
        }).start();

        while (volatileExample.a == 0 ){

        }
        System.out.println(volatileExample.a);
        System.out.println(Thread.currentThread().getName() + "结束");
    }

}

//    volatile boolean b = false;

//    public static void main(String[] args) throws InterruptedException {
//        VolatileExample volatileExample = new VolatileExample();
//
//        new Thread(() -> {
//            volatileExample.business();
//        }).start();
//        Thread.sleep(2000);
//        new Thread(() -> {
//            volatileExample.exchange();
//        }).start();
//    }
//
//    public void business() {
//        try {
//            while (!b) {
//                System.out.println("ss");
//            }
//        } catch (Throwable throwable) {
//
//        }
//
//    }
//
//    public void exchange() {
//        b = true;
//    }
//}
